package cn.tedu.collections;

import java.util.*;

/**
 * Date：2021年11月
 * Author：程Sir
 * Name： JavaSE-API
 * Content:
 *      Comparator 称之为外部比较器，因为Comparator没有和当前自定义类有耦合关系，只是集合比较时，提供了比较规则
 *      比较灵活，因此，被称之为外部比较器，是相对于有强耦合关系的Comparable来讲的！
 *      开发过程中是推荐使用外部比较器d~!
 */
public class Teacher {
    String name;
    int age;

    public Teacher(String name, int age) {

        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Teacher teacher = (Teacher) o;
        return age == teacher.age &&
                Objects.equals(name, teacher.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public static void main(String[] args) {
        List<Teacher> list = new ArrayList<>();
        Collections.addAll(list,
                new Teacher("刘备",66),
                new Teacher("关羽",66),
                new Teacher("张飞",33),
                new Teacher("曹操",33));
        Collections.sort(list, new Comparator<Teacher>() {
            @Override
            public int compare(Teacher o1, Teacher o2) {
                //先进行年龄的判断
                int result =o1.age - o2.age;
                // 如果同岁，再比较名字的首字符
                if (result == 0){ // 年龄比较结果：相同
                    result = o1.getName().charAt(0) - o1.getName().charAt(0);
                }
                return result;
            }
        });
        System.out.println(list);
    }

}
